# -*- coding:utf-8 -*-

from scrapy import Request
from scrapy.spiders import Spider
from scrapyExercise.items import Qqmusic
import json

class QqMusicSpider(Spider):
    name = "qqmusic"
    headers = {"User_Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36"}

    def start_requests(self):
        url = "https://u.y.qq.com/cgi-bin/musics.fcg?-=getUCGI07968589109866175&g_tk=5381&sign=zzal8hksshbu1l5p79011f05e57ce8ee8074e39482c60ceeea&loginUin=0&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq.json&needNewCode=0&data=%7B%22detail%22%3A%7B%22module%22%3A%22musicToplist.ToplistInfoServer%22%2C%22method%22%3A%22GetDetail%22%2C%22param%22%3A%7B%22topId%22%3A4%2C%22offset%22%3A0%2C%22num%22%3A20%2C%22period%22%3A%222020-11-10%22%7D%7D%2C%22comm%22%3A%7B%22ct%22%3A24%2C%22cv%22%3A0%7D%7D"
        yield Request(url, headers=self.headers)

    def parse(self, response, **kwargs):
        item = Qqmusic()
        json_text = response.text
        music_dict = json.loads(json_text).get('detail',{}).get('data',{}).get('songInfoList',[])
        for one_music in music_dict:
            item['song_name'] = one_music['name']
            item['album_name'] = one_music['album']['name']
            item['singer_name'] = one_music['singer'][0]['name']
            item['interval'] = one_music['interval']

            yield item
